package com.studyyoun.demoandroidapplication;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import io.flutter.embedding.android.FlutterActivity;
import io.flutter.embedding.android.FlutterFragment;
import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.embedding.engine.FlutterEngineCache;
import io.flutter.embedding.engine.dart.DartExecutor;


/**
 * Android 原生项目中打开 Flutter
 */

public class OpenFlutterActivity extends AppCompatActivity implements View.OnClickListener {
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_open_flutter);
		
		TextView openFlutterTextView1 = findViewById(R.id.bt_open_1);
		TextView openFlutterTextView2 = findViewById(R.id.bt_open_2);
		TextView openFlutterTextView3 = findViewById(R.id.bt_open_3);
		TextView openFlutterTextView4 = findViewById(R.id.bt_open_4);
		
		openFlutterTextView1.setOnClickListener(this);
		openFlutterTextView2.setOnClickListener(this);
		openFlutterTextView3.setOnClickListener(this);
		openFlutterTextView4.setOnClickListener(this);
		//创建引擎
		FlutterEngine lFlutterEngine = new FlutterEngine(this);
		//设置一些参数 如初始加载显示的路由页面
		lFlutterEngine.getNavigationChannel().setInitialRoute("/test");
		//设置缓存
		lFlutterEngine.getDartExecutor()
				.executeDartEntrypoint(DartExecutor.DartEntrypoint.createDefault());
		//put引擎
		FlutterEngineCache.getInstance().put("test_engine", lFlutterEngine);
		
	}
	
	private void openFlutter() {
		
		FlutterFragment lFlutterFragment = FlutterFragment
				.withCachedEngine("test_engine")
				.build();
		
		getSupportFragmentManager()
				.beginTransaction()
				.add(R.id.fl_open_flutter, lFlutterFragment)
				.commit();
		
	}
	
	private void openFunction3() {
		//打开Flutter 的第三种方式
		startActivity(FlutterActivity
				.withCachedEngine("test_engine")
				.build(this));
	}
	
	private void openFunction2() {
		//打开Flutter 的第二种方式
		startActivity(FlutterActivity
						.withNewEngine()
						.initialRoute("/test")
						.build(this));
	}
	
	private void openFunction1() {
		//创建打开FlutterActivity的意图
		Intent intent = FlutterActivity.createDefaultIntent(this);
		//打开Flutter 的第一种方式
		startActivity(intent);
	}
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.bt_open_1:
				openFunction1();
				break;
			case R.id.bt_open_2:
				openFunction2();
				break;
			case R.id.bt_open_3:
				openFunction3();
				break;
			case R.id.bt_open_4:
				openFlutter();
				break;
		}
		
	}
}